const TOKEN_KEY = 'token'
const USER_INFO_KEY = 'userInfo'

// Token相关操作
export const getToken = () => {
    return localStorage.getItem(TOKEN_KEY)
}

export const setToken = (token) => {
    // 确保存储的 token 带有 Bearer 前缀
    const tokenValue = token.startsWith('Bearer ') ? token : `Bearer ${token}`
    localStorage.setItem(TOKEN_KEY, tokenValue)
}

export const removeToken = () => localStorage.removeItem(TOKEN_KEY)

// 用户信息相关操作
export const getUserInfo = () => {
    const userInfo = localStorage.getItem(USER_INFO_KEY)
    return userInfo ? JSON.parse(userInfo) : null
}

export const setUserInfo = info => {
    localStorage.setItem(USER_INFO_KEY, JSON.stringify(info))
}

export const removeUserInfo = () => localStorage.removeItem(USER_INFO_KEY)

// 清除所有认证信息
export const clearAuth = () => {
    removeToken()
    removeUserInfo()
}

// 初始化认证状态
export const initAuth = () => {
    const token = getToken()
    const userInfo = getUserInfo()
    return {
        token,
        userInfo
    }
}